class Main extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            name: '',
            describe: '',
            number: '',
            list: [
            ],
            ishide: 'none',
            counts: [],
            cate: [],
            start: 0,
            pagesize: 12,
            keyword: '',
            showswitch: !0,
            pagestart: 0,
            clicknew: !1,
            id: 0,
            isshow: 1,
            imgsrc: "",
            audiosrc: "",
            musicclass: '',
            // shelf:'1',  
            cid: "0",
            fileimgshow: !0,
            fileaudioshow: !0,
        };
    }


    inputchange(prop, e) {
        // console.log(prop, 'prop')
        // console.log(e.target.value, 'eeee')
        // let { target } = this.state;
        // target[prop] = e.target.value
        // this.setState({ target })
        this.setState({ [prop]: e.target.value })
    }
    inputchangeradio(prop, e) {
        console.log(prop, 'prop')
        console.log(e.target.value, 'eeee')
        this.setState({ [prop]: e.target.value })
    }

    replaceraw(content) {
        return content.replace('rgb(', 'rgb').replace(new RegExp('rgb', 'g'), "rgb(");
    }

    submit() {
        var { start, imgsrc, name, describe, number, musicclass, cate, cid, ueditor, } = this.state, audiosrc = "", pathimg = "", _this = this, err = '',
            html = ueditor.getContent(), that = this, imgarr = [];
        // time=Number(time)
        number = Number(number)
        // console.log(number, 'number')
        // console.log(audiosrc, 'audiosrc')
        var reg = /^[0-9]{1,3}$/
        // if(audiostate!="isuploadaudio")err="请上传音频"
        // if (imgstate != "isBase64") err = "请上传图片"
        // if(isNaN(time)||time<=0)err="请输入音频时长"
        if (!reg.test(number)) {
            err = "请输入整数"
        }
        if (number > 100 || number < 0 || number == "") err = "请输入0-100的数字"
        // if(!audiosrc)err="请添加音频"
        if (describe == "") err = "请输入描述"
        if (musicclass.length == 0) err = "请选择音频分类"
        // if(shelf.length==0) err = "请选择是否上架"
        if (name == "") err = "请输入名称"
        if (!imgsrc) err = "请添加封面"
        if (err.length > 0) {
            alert(err);
            return
        }
        imgarr = imgarr.concat(imgsrc)
        console.log(imgarr, 'aaa')
        this.uploadimg(imgarr)

    }
    searchinput(e) {
        // console.log(e.target.value,'e.target.value')
        this.setState({ keyword: e.target.value })
    }
    reset() {
        this.setState({ keyword: '', showswitch: !0 });
        this.freshlist(0, 'ALL');
    }
    inputchangeall() {

    }
    componentDidMount() {
        let that = this
        let UE = window.UE
        let ueditor = UE.getEditor('ueditor', {
            autoHeightEnabled: true,
            autoFloatEnabled: true
        });
        ueditor.addListener("ready", function () {
            that.setState({ ueditor }, () => {
                let id = GetQueryString('id')
                if (id != 'null' && id) {
                    that.setState({ id }, () => {
                        that.freshlist()
                    })
                }
            });
        }, 2);
        let statehtml = []
        audiocatebkgetalllist(res => {
            // audiocatempgetlist(res=>{
            if (res.issuccess == 1) {
                // console.log(res.list,'res.data')
                this.inputlist(res.list);
                statehtml.push(
                    <option value="0">请选择</option>
                )
                res.list.forEach((x, i) => {
                    statehtml.push(
                        <option key={i} value={x.id}>{x.name}
                        </option>
                    )
                })
                this.setState({ statehtml })
            }
        })


    }
    freshlist() {
        // title: name, description: describe, src: audiosrc, thumbpath: pathimg, orders: number, cid: musicclass, rawData: that.replaceraw(encodeURIComponent(html)
        let { id } = this.state, that = this;
        audiofindbyids(id, res => {
            if (res.issuccess == 1) {
                var { imgsrc, audiosrc, musicclass, ueditor } = this.state, x = res.data
                ueditor.setContent(that.replaceraw(decodeURIComponent(x.rawData)))
                musicclass = x.cid
                $(`input[name=countmethod][value=${musicclass}]`).prop("checked", "checked");
                imgsrc = `${API_HEAD}imgs/${x.thumbpath}`
                if (x.src && x.src != '') {
                    audiosrc = `${Constant.AUDIOSRC}/${x.src}`
                    that.setState({ audiosrc, fileaudioshow: !1, })
                }
                this.setState({
                    name: x.title, describe: x.description, musicclass, imgsrc, fileimgshow: !1,
                    imgstate: 'isBase64', lbfileimgshow: !1, lbimgstate: 'isBase64', number: x.orders
                })

                // this.formatlist(res.list);
            }
        })
        // this.formatlist(list);

    }
    inputlist(list) {
        var inputhtml = []
        list.forEach((x, i) => {
            inputhtml.push(
                <div key={i} className="radio"><input type="radio" name="countmethod" value={x.id} id={x.id} /><label for={x.id}></label><span>{x.name}</span></div>
            )
        })
        this.setState({ inputhtml, cate: list })
    }

    setpager(pagecount, start) {
        let counts = [];
        for (let i = 1; i < pagecount + 1; i++) {
            counts.push(start + i)
        }
        this.setState({ counts })
    }
    clickpage(e) {
        let { start, pagesize } = this.state
        start = e * pagesize
        this.setState({ pagestart: e, start }, () => {
            this.freshlist(start)
        })
    }
    // 预览图片
    filechangeimg(e) {
        // this.setState({
        //     fileimgshow:!1,
        //     // uploadword: "上传",
        //     imgstate:''
        // })  
        var that = this;
        // var filedata = $('#file3')[0].files[0];
        var filedata = $('#file3')[0].files[0];
        let _name, _fileName;
        _name = $('#file3')[0].value;
        _fileName = _name.substring(_name.lastIndexOf(".") + 1).toLowerCase();
        if (_fileName !== "png" && _fileName !== "jpg" && _fileName !== "gif" && _fileName !== "jpeg") {
            alert("上传图片格式不正确，请重新上传");
        } else {
            this.setState({
                fileimgshow: !1,
                // uploadword: "上传",
                imgstate: ''
            })
            var reader = new FileReader();
            reader.readAsDataURL(filedata);
            reader.onload = function (e) {
                var base64str = e.target.result;
                that.putswiperimglistdata([base64str])
            }
        }
    }
    putswiperimglistdata(target) {


        let { imgsrc } = this.state;
        imgsrc = target[0]
        if (!isBase64(imgsrc)) {
            if (imgsrc.indexOf(`${API_HEAD}`) == -1) {
                imgsrc = `${API_HEAD}imgs/${src}`

            }
        }
        this.setState({
            imgsrc
        })

    }
    // 试听音频
    filechangeaudio(e) {
        let audiosrc = $('#file0')[0].files[0];
        let _name, _fileName;
        console.log(audiosrc, 'audiosrc');
        if (audiosrc.size > 1024 * 60 * 1000) {
            alert('音频不能超过60M')
            return;
        }

        _name = $('#file0')[0].value;
        _fileName = _name.substring(_name.lastIndexOf(".") + 1).toLowerCase();
        if (_fileName !== "mp3" && _fileName !== "wma" && _fileName !== "MP1" && _fileName !== "MP2" && _fileName !== "MPEG") {
            alert("上传音频格式不正确，请重新上传");
        } else {
            this.setState({
                // uploadword: "上传",
                audiosrc,
                audiostate: ''
            })
        }
    }

    clickupload(e) {
        $('#file' + e).click();
    }
    del_img(e) {
        console.log(e, 'eeeeeeee')
        if (e == 3) {
            this.setState({
                imgsrc: '',
                fileimgshow: !0,
                imgstate: ''
            })
        } else if (e == 0) {
            this.setState({
                audiosrc: '',
                fileaudioshow: !0,
                audiostate: ''
            })
        }
    }

    // 上传图片
    uploadimg(arr) {
        let uploadimgarr = [], { audiosrc, imgsrc } = this.state, that = this;
        arr.forEach((x, i) => {
            if (x.indexOf(`${API_HEAD}`) == -1) {
                if (isBase64(x)) {
                    uploadimg(x, res => {
                        if (res.issuccess == 1) {
                            x = `${API_HEAD}imgs/${res.path}`
                            uploadimgarr.push(x)
                        } else {
                            alert(res.msg)
                            err = 1
                            return;
                        }
                    })
                }
            } else {
                uploadimgarr.push(x)
            }
        })
        if (uploadimgarr.length == arr.length) {
            // uploadimgarr.forEach((x, i) => {
            //     if (i == 0) {
            //         imgsrc = x.replace(`${API_HEAD}imgs/`, '')
            //     } 
            // })
            that.setState({ uploadimgarr }, () => {
                if (audiosrc) {
                    that.uploadaudio(audiosrc)
                } else {
                    that.setGoodsaoe()
                }
            })

            // var data = {
            //     title: name, description: describe, src: audiosrc, thumbpath: imgsrc, orders: number, cid: musicclass, rawData: that.replaceraw(encodeURIComponent(html))
            // }
            // if (this.state.id > 0) data['id'] = this.state.id;
            // console.log(data, 'data')
            // Goodsaoe(data, res => {
            //     this.setState({ isloading: !1 })
            //     if (res.issuccess == 1) {
            //         alert(`${this.state.id > 0 ? '修改' : '保存'}成功`);
            //         window.location.href = "./main.html";
            //     } else {
            //         alert(res.msg)
            //     }
            // })
        }
    }
    setGoodsaoe() {
        let { ueditor, name, describe, audiosrc, pathimg, number, imgsrc, uploadimgarr, musicclass } = this.state, that = this, html = ueditor.getContent();

        uploadimgarr.forEach((x, i) => {
            if (i == 0) {
                imgsrc = x.replace(`${API_HEAD}imgs/`, '')
            }
        })
        let pathaudio = audiosrc.replace(`${Constant.AUDIOSRC}/`, '')
        var data = {
            title: name, description: describe, src: pathaudio, thumbpath: imgsrc, orders: number, cid: musicclass, rawData: that.replaceraw(encodeURIComponent(html))
        }
        if (this.state.id > 0) data['id'] = this.state.id;
        console.log(data, 'data')
        audioaoe(data, res => {
            this.setState({ isloading: !1 })
            if (res.issuccess == 1) {
                alert(`${this.state.id > 0 ? '修改' : '保存'}成功`);
                window.location.href = "./audiofrequency.html";
            } else {
                alert(res.msg)
            }
        })
    }

    // 上传音频
    uploadaudio(audiosrc) {
        // let { audiosrc, audiosrc, audiostate } = this.state;
        // if (audiostate == 'isuploadaudio') {
        //     return;
        // }
        console.log(audiosrc, 'audiosrcaudiosrcaudiosrc');

        if (audiosrc) {
            console.log('typefaudiosrc', typeof (audiosrc));

            //audiosrc.indexOf(`${Constant.AUDIOSRC}`) == -1
            if (typeof (audiosrc) == 'object') {
                uploadaudio(audiosrc, res => {
                    console.log(res, 'res');
                    if (res.success == 1) {
                        audiosrc = `${Constant.AUDIOSRC}/${res.path}`
                        // audiohtml.push(
                        //     <div className="audio_warp">
                        //         <audio src={audiosrc} controls="controls" id="audio">Your browser does not support the audio tag.</audio>
                        //         <button className="delaudio" onClick={this.del_img.bind(this,e)}>删除</button>
                        //     </div>
                        // )
                        this.setState({ fileaudioshow: !1, audiosrc, audiostate: 'isuploadaudio' }, () => {
                            this.setGoodsaoe()
                        })

                    } else {
                        alert(res.msg)
                        err = 1
                        return;
                    }
                })
            } else {
                this.setGoodsaoe()
            }






        }
    }
    // // 上传音频
    // uploadaudio(e) {
    //     let { audiosrc, audiosrc, audiostate } = this.state;
    //     if (audiostate == 'isuploadaudio') {
    //         return;
    //     }

    //     if (audiosrc) {
    //         uploadaudio(audiosrc, res => {
    //             console.log(res, 'res');
    //             if (res.success == 1) {
    //                 audiosrc = `${Constant.AUDIOSRC}/${res.path}`
    //                 // audiohtml.push(
    //                 //     <div className="audio_warp">
    //                 //         <audio src={audiosrc} controls="controls" id="audio">Your browser does not support the audio tag.</audio>
    //                 //         <button className="delaudio" onClick={this.del_img.bind(this,e)}>删除</button>
    //                 //     </div>
    //                 // )
    //                 this.setState({ fileaudioshow: !1, audiosrc, audiostate: 'isuploadaudio' })

    //             } else {
    //                 alert(res.msg)
    //                 err = 1
    //                 return;
    //             }
    //         })
    //     }
    // }
    onstatechange(e) {
        let { cid } = this.state, estate = e.target.value;
        console.log(cid, 'cid');
        console.log(e.target.value, 'e.target.value');

        if (cid == estate) return;
        this.setState({ start: 0, cid: estate }, () => {
            this.freshlist(0)
        })
    }
    toback() {
        window.location.href = "./audiofrequency.html";
    }
    render() {
        let { clicknew, counts, listitem, pagestart, describe, number, keyword, showswitch, target, inputhtml, imgsrc, audiosrc, name } = this.state;

        return (
            <div className="breadLinebox">
                <div className='content_wrap panel-default content_wrap'>
                    <div className="breadLine">
                        <span>当前目录</span> > <span onClick={this.toback.bind(this)} style={{ cursor: 'pointer' }}>音频管理</span> > {this.state.id > 0 ? "编辑" : "新建"}音频
                    </div>
                    <div className="content form">
                        <div className="formtitle">
                            <p>{this.state.id > 0 ? "编辑" : "新建"}</p>
                        </div>
                        <div className="formbox">
                            <div className="formcontent">
                                <div className="input-group">
                                    <span className="label input-group-addon">音频图片</span>
                                    <input onChange={this.filechangeimg.bind(this, '3')} type='file' id='file3' style={{ display: "none" }} />
                                    <div className=''>
                                        <img className='fileimg' src={Constant.UPLOADBTN} onClick={this.clickupload.bind(this, '3')} style={{ display: this.state.fileimgshow ? "" : "none" }} />
                                        <div className="img_warp" style={{ display: this.state.fileimgshow ? "none" : "" }}>
                                            <img src={imgsrc} className="img" />
                                            <img className='closeimg' onClick={this.del_img.bind(this, '3')} src='./src/img_close.png' style={{ display: this.state.fileimgshow ? "none" : "" }} />
                                        </div>
                                    </div>
                                </div>
                                <div className="input-group">
                                    <span className="input-group-addon">名称</span>
                                    <input id='name' onChange={this.inputchange.bind(this, 'name')} value={name} type="text" placeholder='请输入名称' className="input" />
                                </div>

                                <div className="input-group countrys">
                                    <span className="input-group-addon">音频分类</span>
                                    <div className="countryname" onChange={this.inputchangeradio.bind(this, 'musicclass')}>
                                        {inputhtml}
                                    </div>
                                </div>

                                <div className="input-group">
                                    <span className="input-group-addon">描述</span>
                                    <textarea id='describe' onChange={this.inputchange.bind(this, 'describe')} value={describe} className="describe" placeholder='请输入描述' rows="10"></textarea>
                                </div>
                                <div className="input-group">
                                    <span className="input-group-addon">音频</span>
                                    <input onChange={this.filechangeaudio.bind(this, '0')} onClick={this.clickupload.bind(this, 0)} type='file' id='file0' style={{ display: this.state.fileaudioshow ? "" : "none" }} />
                                    <div className='detail_btns'>

                                        <div className="audio_warp" style={{ display: this.state.fileaudioshow ? "none" : "" }}>
                                            <audio src={audiosrc} controls="controls" id="audio">Your browser does not support the audio tag.</audio>
                                            <p className="add" onClick={this.del_img.bind(this, 0)}>删除</p>
                                        </div>


                                    </div>
                                </div>
                                <div className="input-group">
                                    <span className="input-group-addon">排序</span>
                                    <input id='name' onChange={this.inputchange.bind(this, 'number')} value={number} type="text" placeholder='请输入0-100的数字' className="input" />
                                    <span className="red">数值越大，排名越前</span>
                                </div>
                                <div className="input-group">
                                    <span className="input-group-addon">富文本</span>
                                    <textarea id={'ueditor'} style={{ height: "30vh" }} ></textarea>
                                </div>

                                <div className='submitbox'>
                                    <button type="button" onClick={this.submit.bind(this)} className="submitbutton">保存</button>
                                    <button type="button" onClick={this.toback.bind(this)} className="submitbutton" style={{ marginLeft: '100' }}>返回</button>
                                </div>
                            </div>
                        </div>
                    </div>


                </div>
            </div>





        )


    }
}





ReactDOM.render(
    <div>
        <TopLine />
        <div id='body'>
            <LeftMenu code='audiofrequency' />
            <Main />
        </div>
    </div>
    // <Barrage/>
    , $('.container')[0]
)
